/*
 * TransactionsLogMonitor.java    ver   23/nov/2009
 *
 * Copyright (c) 2009 mentalsmash.org
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * The use of the Apache License does not indicate that this project is
 * affiliated with the Apache Software Foundation.
 */
package org.mentalsmash.tazio.transactions.log;

import java.util.Date;

import javax.management.JMException;
import javax.management.MBeanServer;
import javax.management.ObjectName;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.inject.Inject;
import com.google.inject.name.Named;

/**
 * Standard MBean implementation that monitors the TransactionsLog, for
 * statistics purposes
 * 
 * @version 0.0.1 23/nov/2009
 * @author Andrea Reale <andrea.reale@gmail.com>
 * 
 */
public class TransactionsLogMonitor implements TransactionsLogMonitorMBean {

    private final static Logger log = LoggerFactory
	    .getLogger(TransactionsLogMonitor.class);

    public static final String NAME = "TransactionsLogMonitor";
    
    private final static int MILLIS_IN_A_MINUTE = 60000;
    private final TransactionsLog toMonitor;
    private final Date startedMonitoring;

    private final String name;
    
    @Inject
    TransactionsLogMonitor(final TransactionsLog toMonitor,@Named(NAME) String name) {
	
	this.name = name;
	this.toMonitor = toMonitor;
	startedMonitoring = new Date();

	if (!(toMonitor instanceof BasicTransactionsLog)) {
	    log.error("System log is not an instance of BasicTransactionsLog,"
		    + " some of the monitoring "
		    + "facilities will not be available");
	}

    }

    @Inject
    public void register(final MBeanServer server) {
	try {
	    final ObjectName name = new ObjectName(
		    "org.mentalsmash.tazio.transactions:type="+
		    "TransactionsLogMonitor");
	    server.registerMBean(this, name);
	} catch (final JMException e) {
	    log.error("Unable to register MBean", e);
	}
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * org.mentalsmash.tazio.transactions.control.TransactionsLogMonitorMBean
     * #getCommitsPerMinute()
     */
    @Override
    public double getCommitsPerMinute() {
	final int numCommits = toMonitor.getNumCommits();

	return computePerMinuteStatistic(numCommits);

    }

    @Override
    public double getRollbacksPerMinute() {
	final int numRollbakcs = toMonitor.getNumRollbacks();
	return computePerMinuteStatistic(numRollbakcs);
    }

    private double computePerMinuteStatistic(final int total) {
	final Date now = new Date();
	final double minutesElapsed = (now.getTime() - startedMonitoring
		.getTime())
		/ (double) MILLIS_IN_A_MINUTE;

	return (total) / minutesElapsed;
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * org.mentalsmash.tazio.transactions.control.TransactionsLogMonitorMBean
     * #getNumActiveTransactions()
     */
    @Override
    public int getNumActiveTransactions() {
	return toMonitor.getNumActive();
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * org.mentalsmash.tazio.transactions.control.TransactionsLogMonitorMBean
     * #getNumCommittedTransactions()
     */
    @Override
    public int getNumCommittedTransactions() {
	return toMonitor.getNumCommits();
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * org.mentalsmash.tazio.transactions.control.TransactionsLogMonitorMBean
     * #getNumRolledbackTransactions()
     */
    @Override
    public int getNumRolledbackTransactions() {
	return toMonitor.getNumRollbacks();
    }

    /*
     * (non-Javadoc)
     * 
     * @seeorg.mentalsmash.tazio.transactions.log.TransactionsLogMonitorMBean#
     * getAverageTxDuration()
     */
    @Override
    public double getAverageTxDuration() {
	// Notice that this method will break if using an instance of a
	// transaction log
	// that is not BasicTransactionsLog
	if (!(toMonitor instanceof BasicTransactionsLog)) {
	    // Cannot monitor if not an instance of BasicTransactionsLog
	    return -1;
	}
	final BasicTransactionsLog log = (BasicTransactionsLog) toMonitor;

	return log.computeAvgTxDuration();
    }

    /*
     * (non-Javadoc)
     * 
     * @seeorg.mentalsmash.tazio.transactions.log.TransactionsLogMonitorMBean#
     * getTxValidityTime()
     */
    @Override
    public int getTxValidityTime() {
	// Notice that this method will break if using an instance of a
	// transaction log
	// that is not BasicTransactionsLog
	if (!(toMonitor instanceof BasicTransactionsLog)) {
	    // Cannot monitor if not an instance of BasicTransactionsLog
	    return -1;
	}
	final BasicTransactionsLog log = (BasicTransactionsLog) toMonitor;
	return log.getTransactionValidity();
    }

    /*
     * (non-Javadoc)
     * 
     * @seeorg.mentalsmash.tazio.transactions.log.TransactionsLogMonitorMBean#
     * setTxValidityTime(int)
     */
    @Override
    public void setTxValidityTime(final int minutes) {
	// Notice that this method will break if using an instance of a
	// transaction log
	// that is not BasicTransactionsLog
	if (!(toMonitor instanceof BasicTransactionsLog)) {
	    // Cannot monitor if not an instance of BasicTransactionsLog
	    return;
	}
	final BasicTransactionsLog log = (BasicTransactionsLog) toMonitor;

	log.setTransactionValidity(minutes);

    }

}
